<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 文字警告区域 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="cat_row">
        <el-col :span="2.3">
          <span>选择商品分类：</span>
        </el-col>
        <el-col :span="21" class="cate_cascader">
          <!-- 级联选择框 -->
          <el-cascader
            v-model="CateKeys"
            :options="cataList"
            :props="cascaderProps"
            @change="CateKeysChange"
            clearable
            ref="cascaderRef"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tab页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 动态参数面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            :disabled="isBtnDisabled"
            @click="addParmamdialogVisible = true"
            >添加参数</el-button
          >
          <!-- 动态参数表格 -->
          <el-table :data="manyTableDate" border>
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环展示tag标签 -->
                <el-tag
                  v-for="(item, i1) in scope.row.attr_vals"
                  :key="i1"
                  closable
                  @close="deleteParamsProp(i1, scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 输入的tab标签 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加标签的标签按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"> </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini"
                  >编辑</el-button
                >
                <el-button type="danger" icon="el-icon-delete" size="mini"
                  >删除</el-button
                ></template
              >
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            :disabled="isBtnDisabled"
            @click="addParmamdialogVisible = true"
            >添加属性</el-button
          >
          <!-- 静态参数表格 -->
          <el-table :data="onlyTableDate" border>
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环展示tag标签 -->
                <el-tag
                  v-for="(item, i1) in scope.row.attr_vals"
                  :key="i1"
                  closable
                  @close="deleteParamsProp(i1, scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 输入的tab标签 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加标签的标签按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"> </el-table-column>
            <el-table-column prop="attr_name" label="属性名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini"
                  >编辑</el-button
                >
                <el-button type="danger" icon="el-icon-delete" size="mini"
                  >删除</el-button
                ></template
              >
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数的对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addParmamdialogVisible"
      width="50%"
      @close="addParamsDialogClose"
    >
      <!-- 添加参数对话框的表单区域 -->
      <el-form
        :model="addParamsFrom"
        :rules="addParamsFromRules"
        ref="addParamsFromRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addParamsFrom.attr_name"></el-input> </el-form-item
      ></el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParmamdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParmamsFormBtn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 页面默认选择
      activeName: 'many',
      // 级联选择框分类数据
      cataList: [],
      //   保存级联选择框选中的分类的ids
      CateKeys: [],
      // 级联选择框配置对象
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover',
      },
      //   动态参数数据
      manyTableDate: [],
      //   静态参数数据
      onlyTableDate: [],
      // 控制添加参数对话框的显示与隐藏
      addParmamdialogVisible: false,
      // 添加参数表单对象
      addParamsFrom: {
        attr_name: ''
      },
      // 添加参数表单验证规则对象
      addParamsFromRules: {
        attr_name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ]
      }


    }
  },
  created() {
    //   获取所有商品分类列表
    this.getCateList()
  },
  methods: {
    //   获取所有商品分类列表
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类失败！')
      }
      this.cataList = res.data
      console.log(this.cataList);
    },
    // 监听级联选择框变化
    async CateKeysChange() {
      this.$refs.cascaderRef.dropDownVisible = false
      //   console.log(this.CateKeys);
      this.getParamsList()

    },
    // 获取参数列表数据
    async getParamsList() {
      // 如果选择的不是三级分类
      if (this.CateKeys.length !== 3) {
        this.CateKeys = []
        this.manyTableDate = []
        this.onlyTableDate = []
        return this.$message.error('请选择三级分类！')
      }
      //   选中三级分类
      else {
        //    根据所选分类的id和当前所处的面板，获取对应的参数
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: { sel: this.activeName }
        })
        if (res.meta.status !== 200) {
          return this.$message.error('获取参数列表失败！')
        }
        res.data.forEach(item => {
          // 控制当前行输入框tab标签的显示与隐藏
          item.inputVisible = false
          // 输入框tab标签的内容
          item.inputValue = ''
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []

        });
        console.log(res.data);
        if (this.activeName === 'many') {
          this.manyTableDate = res.data
        }
        else {
          this.onlyTableDate = res.data
        }
      }
    },
    // 页签点击事件
    handleTabClick() {
      //   console.log(this.activeName);
      this.getParamsList()
    },
    // 添加参数对话框关闭事件
    addParamsDialogClose() {
      this.$refs.addParamsFromRef.resetFields()
    },
    // 添加参数表单确定处理事件
    addParmamsFormBtn() {
      this.$refs.addParamsFromRef.validate(async volid => {
        if (!volid) return
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addParamsFrom.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) {
          return this.$message.error('添加参数失败！')
        }
        this.$message.success('添加参数成功！')
        this.getParamsList()
        this.addParmamdialogVisible = false

      })
    },
    // tag标签输入框的enter键弹起或者鼠标失去焦点都会执行事件
    async handleInputConfirm(row) {
      // 输入内容全是空格
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
      }
      // 输入内容合法
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      this.saveAttr_vals(row)


    },
    async saveAttr_vals(row) {

      //  发起请求，保存这次操作
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) {
        return this.$message.error('修改参数项失败！')
      }
      this.$message.success('修改参数成功！')
      row = res.data
    },
    // 添加tab标签的点击事件
    showInput(row) {
      row.inputVisible = true
      // 让文本框自动获得焦点
      // $nextTick方法的作用，就是当页面上的元素被重新渲染之后，才会执行回调函数
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      })
    },
    // tag标签删除事件
    deleteParamsProp(i, row) {
      row.attr_vals.splice(i, 1)
      this.saveAttr_vals(row)
    }
  },
  computed: {
    //   如果按钮需要被禁用，则返回True,否则返回false
    isBtnDisabled() {
      if (this.CateKeys.length !== 3) {
        return true
      }
      else {
        return false
      }
    },
    // 当前选中的三级分的id
    cateId() {
      if (this.CateKeys.length === 3) {
        return this.CateKeys[2]
      }
      else {
        return null
      }
    },
    //动态计算添加参数对话框的标题文本
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      else {
        return '静态属性'
      }
    }
  }
}
</script>
<style lang="less" scoped>
.cat_row {
  margin: 15px 0;
  line-height: 41px;
}
.cate_cascader {
  width: 30%;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>